<template>
  <div class="chat-container">
    <!-- 左侧联系人列表 -->
    <div class="contact-list">
      <el-card shadow="hover">
        <template #header>
          <div class="contact-header">
            <span>联系人</span>
          </div>
        </template>
        <el-scrollbar height="calc(100vh - 180px)">
          <div
              v-for="contact in contacts"
              :key="contact.id"
              class="contact-item"
              :class="{ 'active': activeContact?.id === contact.id }"
              @click="selectContact(contact)"
          >
            <el-avatar :size="40" :src="'/img'+contact.tx" />
            <div class="contact-info">
              <span class="contact-name">{{ contact.nc }}</span>
              <span class="last-message">{{ contact.lastMessage || '暂无消息' }}</span>
            </div>
            <el-badge v-if="contact.unread > 0" :value="contact.unread" class="unread-badge" />
          </div>
        </el-scrollbar>
      </el-card>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <el-card v-if="activeContact" shadow="never">
        <template #header>
          <div class="chat-header">
            <el-avatar :size="40" :src="'/img'+activeContact.tx" />
            <span class="contact-name">{{ activeContact.nc }}</span>
          </div>
        </template>
        <el-scrollbar ref="messageScroll" height="calc(100vh - 250px)">
          <div class="message-container">
            <div
                v-for="(message, index) in messages"
                :key="index"
                class="message-item"
                :class="{ 'sent': message.fszId === currentUser.id, 'received': message.fszId !== currentUser.id }"
            >
              <div class="message-content">
                <div v-if="message.text">{{ message.text }}</div>
                <div class="message-time">{{ formatTime(message.time) }}</div>
              </div>
            </div>
          </div>
        </el-scrollbar>
        <div class="message-input">
          <el-input
              v-model="newMessage"
              :autosize="{ minRows: 1, maxRows: 4 }"
              type="textarea"
              placeholder="输入消息..."
              @keyup.enter="sendTextMessage"
          />
          <el-button
              type="primary"
              :disabled="!newMessage.trim()"
              @click="sendTextMessage"
          >
            发送
          </el-button>
        </div>
      </el-card>
      <div v-else class="empty-chat">
        <el-empty description="请从左侧选择聊天对象" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import axios from "axios"

const userStore = useUserStore()
const myId = userStore.id

// 当前用户信息（根据用户表字段）
const currentUser = ref({
  id: myId,
  yhm: '',
  nc: '',
  tx: '',
  phone: '',
  email: ''
})

// 联系人列表（根据用户表字段）
const contacts = ref<Array<{
  id: number
  yhm: string
  nc: string
  tx: string
  lastMessage?: string
  unread: number
}>>([])

// 当前选中的联系人
const activeContact = ref<any>(null)

// 消息列表（根据用户表字段）
const messages = ref<Array<{
  id?: number
  fszId: number  // 发送者ID
  jszId: number  // 接收者ID
  text: string   // 消息内容
  time: string | null   // 发送时间
}>>([])

// 新消息内容
const newMessage = ref('')

// 消息滚动条引用
const messageScroll = ref<any>(null)

// 获取当前用户信息
const getUserInfo = async () => {
  try {
    const response = await fetch('/api/user/' + myId)
    const data = await response.json()
    console.log(data)
    currentUser.value = {
      id: data.id,
      yhm: data.yhm,
      nc: data.nc,
      tx: data.tx,
      phone: data.phone,
      email: data.email
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取联系人列表
const getContacts = async () => {
  try {
    const response = await fetch('/api/user/fan/' + myId)
    const data = await response.json()
    contacts.value = data.map((user: any) => ({
      id: user.id,
      yhm: user.yhm,
      nc: user.nc,
      tx: user.tx,
      lastMessage: '',
      unread: 0
    }))
  } catch (error) {
    console.error('获取联系人列表失败:', error)
  }
}

// 选择联系人
const selectContact = async (contact: any) => {
  activeContact.value = contact
  // 加载历史消息
  await loadHistoryMessages(contact.id)
}

// 加载历史消息
const loadHistoryMessages = async (jszId: number) => {
  try {
    // 获取我发送给对方的消息
    const { data: sentMessages } = await axios(`/api/chat/text/${myId}/${jszId}`)
    console.log("我发送的消息：", sentMessages)

    // 获取对方发送给我的消息
    const { data: receivedMessages } = await axios(`/api/chat/text/${jszId}/${myId}`)
    console.log("对方发送的消息：", receivedMessages)

    // 合并两个数组
    const allMessages = [...sentMessages, ...receivedMessages]

    // 处理数据并按时间排序
    messages.value = allMessages
        .map((msg: any) => ({
          id: msg.id,
          fszId: msg.fszId,
          jszId: msg.jszId,
          text: msg.text,
          time: msg.time
        }))
        .sort((a, b) => {
          // 按时间排序，如果 time 为 null 则排在最后
          if (!a.time && !b.time) return 0
          if (!a.time) return 1
          if (!b.time) return -1
          return new Date(a.time).getTime() - new Date(b.time).getTime()
        })

    console.log("合并后的消息列表：", messages.value)

    scrollToBottom()
  } catch (error) {
    console.error('加载历史消息失败:', error)
  }
}

// 发送文本消息
const sendTextMessage = async () => {
  if (!newMessage.value.trim() || !activeContact.value) return

  const message = {
    fszId: myId,
    jszId: activeContact.value.id,
    text: newMessage.value,
    time: new Date().toISOString().replace('T', ' ').substring(0, 19)
  }
  console.log("发送的消息：", message)
  try {
    // 发送消息到后端
    const response = await axios.post('/api/chat', message)

    // 检查后端是否成功处理
    if (response.status === 200) {
      // 将消息添加到本地消息列表
      messages.value.push(message)

      // 清空输入框
      newMessage.value = ''

      // 滚动到底部
      scrollToBottom()

      console.log('消息发送成功:', response.data)
    } else {
      ElMessage.error('消息发送失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('消息发送失败')
  }
}

// 滚动到消息底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageScroll.value) {
      messageScroll.value.setScrollTop(messageScroll.value.wrapRef.scrollHeight)
    }
  })
}

// 时间格式化
// const formatTime = (timeString: string | null) => {
//   if (!timeString) {
//     return '' // 处理 time 为 null 或 undefined 的情况
//   }
//   const date = new Date(timeString.replace(' ', 'T'))
//   return (
//       date.getHours().toString().padStart(2, '0') + ':' +
//       date.getMinutes().toString().padStart(2, '0')
//   )
// }
const formatTime = (timeString: string | null) => {
  if (!timeString) {
    return '' // 处理 time 为 null 或 undefined 的情况
  }

  try {
    let date: Date;

    // 处理 "yyyy-MM-dd HH:mm:ss" 格式
    if (timeString.includes('-') && timeString.includes(':') && timeString.includes(' ')) {
      const [datePart, timePart] = timeString.split(' ');
      const [year, month, day] = datePart.split('-').map(Number);
      const [hour, minute, second] = timePart.split(':').map(Number);
      date = new Date(year, month - 1, day, hour, minute, second || 0);
    }
    // 处理 ISO 格式
    else if (timeString.includes('T')) {
      date = new Date(timeString);
    }
    // 其他格式尝试直接解析
    else {
      date = new Date(timeString);
    }

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return ''; // 返回空字符串如果日期无效
    }

    // 格式化为 HH:MM
    return (
        date.getHours().toString().padStart(2, '0') + ':' +
        date.getMinutes().toString().padStart(2, '0')
    )
  } catch (error) {
    console.error('时间格式化错误:', error, '原始时间字符串:', timeString);
    return ''; // 出错时返回空字符串
  }
}

// 初始化
onMounted(() => {
  getUserInfo()
  getContacts()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 60px);
  background-color: #f5f5f5;
}

.contact-list {
  width: 300px;
  border-right: 1px solid #e6e6e6;
  background-color: white;
}

.contact-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.contact-item:hover {
  background-color: #f5f5f5;
}

.contact-item.active {
  background-color: #e6f7ff;
}

.contact-info {
  margin-left: 12px;
  flex: 1;
  overflow: hidden;
}

.contact-name {
  display: block;
  font-weight: 500;
  margin-bottom: 4px;
}

.last-message {
  display: block;
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unread-badge {
  margin-left: auto;
}

.chat-area {
  flex: 1;
  background-color: white;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.chat-header .contact-name {
  margin-left: 10px;
  font-size: 16px;
  font-weight: 500;
}

.message-container {
  padding: 20px;
}

.message-item {
  margin-bottom: 16px;
  display: flex;
}

.message-item.sent {
  justify-content: flex-end;
}

.message-item.received {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 8px;
  position: relative;
}

.message-item.sent .message-content {
  background-color: #1890ff;
  color: white;
}

.message-item.received .message-content {
  background-color: #f0f0f0;
  color: #333;
}

.message-time {
  font-size: 12px;
  margin-top: 4px;
  text-align: right;
}

.message-item.sent .message-time {
  color: rgba(255, 255, 255, 0.7);
}

.message-item.received .message-time {
  color: rgba(0, 0, 0, 0.45);
}

.message-input {
  padding: 10px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.empty-chat {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
